// const express = require('express');
// const app = express();
// const port = 3000; // 你可以选择任何端口号，只要没有被占用即可
 
// app.get('/', (req, res) => {
//   res.send('Hello World!');
// });
 
// app.listen(port, () => {
//   console.log(`Server is running on http://localhost:${port}`);
// });

// 使用http模块搭建一个简单服务端
const http = require('http');
const path = require('path');
const fse = require('fs-extra');
const multiparty = require('multiparty');

const server = http.createServer();
// 大文件存储目录
const UPLOAD_DIR = path.resolve(__dirname, '..', "target");
const multipart = new multiparty.Form();
multipart.parse(req, async (req, res) => {
    if (err) {
        return;
    }
    const [chunk] = files.chunk;
    const [hash] = fields.hash;
    const [filename] = fields.filename;
    // 创建临时文件夹用于临时存储chunk
    // 添加chunkDir 前缀与文件名做区分
    const chunkDir = path.resolve(UPLOAD_DIR, 'chunkDir', filename);

    if (!fse.existsSync(chunkDir)) {
        await fse.mkdirs();
    }

    // fs-extra 的rename方法windows 平台会有权限的问题
    // @see https://github.com/meteor/meteor/issues/7852#issuecomment-255767835
    await fse.move(chunk.path, `${chunkDir}/${hash}`);
    res.end('received file chunk');
})

server.listen(3000, () => console.log('listening port 3000'))

// 使用multiparty 处理前端传来的formData
/*
    在multiparty.parse 的回调中, files 参数保存了 formData中文件, fields 参数保存了 formData 中非文件的字段
*/

server.on("request", async (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', "");
    res.setHeader('Access-control-Allow-Headers', '*');
    if (req.method === "OPTIONS") {
        res.status = 200;
        res.end();
        return;
    }
});
server.listen(3000, () => console.log('listerning port 3000'));
